#! /usr/bin/env python  
# -*- coding: utf-8 -*-  
# mongoDB的常用操作
# http://api.mongodb.org/python/current/index.html
# @author yuqingxu@ctrip.com
# @version 2015-08-31  11:00

from pymongo import MongoClient
from pymongo.cursor import CursorType
import datetime

class MOongoDBUtil:
    def initConfig(self):
        global client, db

        host = "mongodb.vincent78.com"
        port = 27017
        userName = "test"
        passwd = "test"
        dbname = "test"
        # 创建连接
        # conn = pymongo.Connection('10.11.1.70',27017)
        # 连接数据库
        # db = conn.study
        # db = conn['study']
        # 打印所有聚集名称，连接聚集
        # print u'所有聚集:',db.collection_names()
        client = MongoClient(host, port)
        client.test.authenticate(userName, passwd)
        print u'库名:', dbname
        db = client[dbname]
        print u'所有的collections', db.collection_names()

    # 查询
    def find(self, collectionName, filter=None, projection=None, skip=0, limit=0, no_cursor_timeout=False
             , cursor_type=CursorType.NON_TAILABLE
             , sort=None, allow_partial_results=False, oplog_replay=False, modifiers=None, manipulate=True):
        for item in db[collectionName].find(filter, projection
                , skip, limit, no_cursor_timeout, cursor_type, sort
                , allow_partial_results, oplog_replay, modifiers, manipulate):
            print item

    def find(self, collectionName):
        return db[collectionName].find()

    # 添加
    def insert(self, collectionName, doc):
        global db
        doc["timesnap_create"] = datetime.datetime.utcnow()
        doc["timesnap_modify"] = datetime.datetime.utcnow()

        result = db[collectionName].insert_one(doc)
        return result.inserted_id

    def update(self, filter, update, upsert=False):
        pass

    def delete(self, doc):
        pass

    def __init__(self):
        self.client = MongoClient()
        self.db = ""
        self.initConfig()

        # def __init__(self,configFile):
        #     global host,port,userName,passwd,dbname
        #     initConfig


if __name__ == "__main__":
    dbUtil = MongoDBUtil()
    # print u'inserted objectId',dbUtil.insert(dbname,{"id":1,"name":"ttttt"})
    # print u'the find obj is:',dbUtil.find(dbname,{"id":1})
    print u'the find obj is:'
    for item in dbUtil.find("test"):
        print (item["name"])
